package com.xm.xmwa1706090.service.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.xm.xm.dto.ResultDto;
import com.xm.xm.dto.SearchDto;
import com.xm.xm.util.ErrorCode;
import com.xm.xmwa1706090.service.dto.QbEquipmentDto;
import com.xm.xmwa1706090.service.mapper.QbEquipmentMapper;
import com.xm.xmwa1706090.service.mapper.QbExplainMapper;
import com.xm.xmwa1706090.service.model.QbEquipment;
import com.xm.xmwa1706090.service.service.QbEquipmentService;
import com.xm.xmwa1706090.service.util.CoordinateConvert;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;

/**
 * 杭州新苗网络科技有限公司
 *
 * @author meihf
 * @date 2017/07/07
 * @description
 */
@Service("qbEquipmentService")
public class QbEquipmentServiceImpl extends ServiceImpl<QbEquipmentMapper, QbEquipment> implements QbEquipmentService {

    @Autowired
    QbEquipmentMapper qbEquipmentMapper;

    @Override
    public ResultDto nearByBikes(SearchDto searchDto) {
        ResultDto resultDto = new ResultDto();
        JSONObject filed = searchDto.getFiled();
        searchDto.setPageNo((searchDto.getPageNo() - 1) * searchDto.getPageSize());
        try {
            if (!filed.has("lng") || !filed.has("lat")) {
                resultDto.setMsg(ErrorCode.E10011);
                resultDto.setCode(ErrorCode.C10011);
                return resultDto;
            } else {
                double lng = filed.getDouble("lng");
                double lat = filed.getDouble("lat");
                filed.put("pageNo",searchDto.getPageNo());
                filed.put("pageSize",searchDto.getPageSize());
                List<QbEquipmentDto> qbEquipments =qbEquipmentMapper.selectNearByBikes(filed);
                if (qbEquipments.size()==0){
                    resultDto.setCode(ErrorCode.C11001);
                    resultDto.setMsg(ErrorCode.E11001);
                    return resultDto;
                }else {
                    qbEquipments.forEach((bike)->{
                        double distance = CoordinateConvert.getDistance(lat,lng,bike.getLat(),bike.getLng());
                        if (distance>1000){
                            qbEquipments.remove(bike);
                        }else {
                            bike.setDistance(distance);
                        }
                    });
                    resultDto.setData(qbEquipments);
                }
            }
        } catch (RuntimeException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            resultDto.setCode(ErrorCode.C10013);
            resultDto.setMsg(ErrorCode.E10013);
        }
        return resultDto;
    }
}

